
import os,sys
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)) + '/../../')

import json
import requests
import datetime

try:
    from .urls import gtokenUrl, getJsTicket
    from .data import info
except:
    from app.envs.urls import gtokenUrl, getJsTicket
    from app.envs.data import info

#import logging
from db.querydb import request_db_param
#logger = logging.getLogger('info')


class WXToken:
    def __init__(self):
        pass

    @staticmethod
    def updateToken(appname):
        #获取token
        url = gtokenUrl.format(**info)
        response = requests.get(url, verify=False)
        token = json.loads(response.text)['access_token']
        # 获取js_ticket
        getJsurl = getJsTicket.format(**{'token':token})
        tmp = requests.get(getJsurl, verify=False)
        tresult = json.loads(tmp.text)
        if tresult.get('errcode') == 0:
            js_ticket = tresult.get('ticket')
        else:
            #logger.info('获取js_ticket失败')
            return 'get js ticket failed'
        #
        getTime = datetime.datetime.now()
        #logger.info('在时间 ：{0} 获取token ：{1}，jsTicket：{2}， 7200s后失效'.format(str(getTime), token, tresult.get('ticket')))
        #写入数据库
        dict_data = dict()
        dict_data['appname'] = appname
        dict_data['token'] = token
        dict_data['jsticket'] = js_ticket
        ret = request_db_param('updateToken', dict_data)
        return ret[1]

    @staticmethod
    def getToken(appname):
        dict_data = dict()
        dict_data['appname'] = appname
        ret = request_db_param('getToken', dict_data)
        result = eval(str(ret[1]))
        errcode = result.get('errcode')
        if ( errcode is not 0):
            return None
        tokeninfo = result.get('tokenInfo')
        return tokeninfo.get('token')

    @staticmethod
    def getJsTicket(appname):
        dict_data = dict()
        dict_data['appname'] = appname
        ret = request_db_param('getToken', dict_data)
        result = eval(str(ret[1]))
        errcode = result.get('errcode')
        if ( errcode is not 0):
            return None
        tokeninfo = result.get('tokenInfo')
        return tokeninfo.get('jsticket')



if __name__ == "__main__":
    wxtoken = WXToken()
    ret = wxtoken.updateToken("niuneng")
    import time
    print('update token at {} result is {}'.format(time.ctime(), str(ret)))







